package no.saiboten.milkywave.mail;

import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import no.saiboten.milkywave.entity.User;

import org.springframework.stereotype.Component;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@Component
public class MailSenderImpl implements MailSender {

	private static final Logger LOGGER = Logger.getLogger(MailSenderImpl.class
			.getName());

	public boolean activated;

	public MailSenderImpl() {
		activated = true;
	}

	@Override
	public boolean sendMail(String mail, String subject, String content) {

		if (!activated) {
			LOGGER.info("Mailsending is deactivated. Will not send mail.");
			return false;
		}

		LOGGER.info(MessageFormat.format(
				"Sending mail to {0} with subject {1} and content {2}", mail,
				subject, content));

		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("jonesy664@live.no",
					"Milkywave alarm"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
					mail, subject));
			msg.setSubject(subject);
			msg.setText(content);
			Transport.send(msg);
			LOGGER.info("Mail sent!");
			return true;
		} catch (AddressException e) {
			LOGGER.info(e.getMessage());
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
			LOGGER.info(e.getMessage());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			LOGGER.info(e.getMessage());
		}
		LOGGER.info("Could not send mail.");
		return false;
	}

	@Override
	public boolean isActivated() {
		return activated;
	}

	@Override
	public void setActivated(boolean activated) {
		this.activated = activated;
	}

	@Override
	public void sendMailToAllMembers(String subject, String content) {
		Objectify ofy = ObjectifyService.begin();
		Query<User> mails = ofy.query(User.class);
		List<User> users = mails.list();
		for (User user : users) {
			sendMail(user.getMail(), subject, content);
		}
	}

}
